package net.gdface.facedb;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import gu.sql2java.exception.RuntimeDaoException;
import gu.sql2java.manager.SqliteInitializer;
import net.gdface.facedb.db.Constant;
import net.gdface.sdk.BaseFaceApiLocal;

/**
 * 基于SQLite本地数据库的{@link net.gdface.facedb.FaceDb}实例初始化
 * @author guyadong
 *
 */
public class FacedbSqliteInitializer implements LocalConstant,Constant{

	private FacedbSqliteInitializer() {
	}
	/**
	 * 创建基于SQLite的{@link net.gdface.facedb.FaceDb}实例
	 * @param faceapiLocal {@link net.gdface.sdk.FaceApi}本地实例
	 * @param db SQLite数据库文件位置,如果为{@code null},
	 * 						必须在{@code properties}中定义'sqlite.db',否则忽略{@code properties}中定义的'sqlite.db'
	 * @param properties FaceDb 配置参数,参见{@link LocalConstant}定义,可为{@code null}
	 * @return {@link FaceDbGenericDecorator}实例
	 */
	public static FaceDbGenericDecorator init(BaseFaceApiLocal faceapiLocal, File db, Properties properties){
		if(null == properties){
			properties = new Properties();
		}
		if(null == db && properties.containsKey(SQLITE_DB)){
			// db 为null时使用properties中sqlite.db定义的值
			db = new File(properties.getProperty(SQLITE_DB));
		}
		boolean runInMemory = Boolean.valueOf(properties.getProperty(SQLITE_RUNINMEMORY, "false"));
		
		properties.setProperty(JdbcProperty.ALIAS.key, ALIAS_NAME);
		URL createSql = FacedbSqliteInitializer.class.getResource("/sql/create_table.sql");
		SqliteInitializer initializer = SqliteInitializer.init(db, createSql, runInMemory, properties);
		if(properties.containsKey(SQLITE_BACKUP_INTERNAL)){
			int backupIntervalSeconds = Integer.valueOf(properties.getProperty(SQLITE_BACKUP_INTERNAL));
			initializer.setBackupIntervalSeconds(backupIntervalSeconds);
		}
		if(!properties.containsKey(STORE_LOCAL_ROOT)){
			// 没有指定图像存储位置,则默认定义为与数据库同级的store文件夹下
			try {
				File store = new File(db.getParent(),"store");
				properties.setProperty(STORE_LOCAL_ROOT, store.getCanonicalPath());
			} catch (IOException e) {
				throw new RuntimeDaoException(e);
			}
		}
		if(!properties.containsKey(STORE_TARGET)){
			properties.setProperty(STORE_TARGET, StoreType.FILE.name());
		}
		
		TableManagerInitializerSupport.setLocalPropertiesFile(properties);
		return new FaceDbGenericDecorator(new FacedbFull(faceapiLocal));
	}
}
